
package com.sinosoft.ptas.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import com.sinosoft.framework.core.common.exception.BusinessException;
import com.sinosoft.framework.core.common.utils.StringUtil;
import com.sinosoft.ptas.control.dto.ReportDataToExcel;
import com.sinosoft.ptas.control.dto.ReportRemindData;
import com.sinosoft.ptas.control.dto.RetrieveReportData;
import com.sinosoft.ptas.dao.AnnualTargetMapper;
import com.sinosoft.ptas.dao.IndexMapper;
import com.sinosoft.ptas.dao.MapEntityMapper;
import com.sinosoft.ptas.dao.ReportEntityMapper;
import com.sinosoft.ptas.dao.TargetsOfImplPhaseMapper;
import com.sinosoft.ptas.entity.AnnualTargetEntity;
import com.sinosoft.ptas.entity.IndexEntity;
import com.sinosoft.ptas.entity.MapEntity;
import com.sinosoft.ptas.entity.ReportEntity;
import com.sinosoft.ptas.entity.TargetsOfImplPhaseEntity;
import com.sinosoft.ptas.service.ReportService;
import com.sinosoft.ptas.system.commom.AuditConstant;
import com.sinosoft.ptas.system.commom.ExceptionConstant;

/**
 * 整体审核表service接口实现
 * @author zhangxiaolong
 *
 */
@Service
@Validated
public class ReportServiceImpl implements ReportService {
	ReportEntityMapper reportMapper;
	
	TargetsOfImplPhaseMapper targetsOfImplPhaseMapper;
	
	AnnualTargetMapper annualTargetMapper;
	IndexMapper indexMapper;
	
	MapEntityMapper mapEntityMapper;
	
	

	public void setMapEntityMapper(MapEntityMapper mapEntityMapper) {
		this.mapEntityMapper = mapEntityMapper;
	}

	public void setAnnualTargetMapper(AnnualTargetMapper annualTargetMapper) {
		this.annualTargetMapper = annualTargetMapper;
	}

	public void setIndexMapper(IndexMapper indexMapper) {
		this.indexMapper = indexMapper;
	}

	public void setReportMapper(ReportEntityMapper reportMapper) {
		this.reportMapper = reportMapper;
	}

	public void setTargetsOfImplPhaseMapper(
			TargetsOfImplPhaseMapper targetsOfImplPhaseMapper) {
		this.targetsOfImplPhaseMapper = targetsOfImplPhaseMapper;
	}

	/**
	 * 增加整体审核表
	 * @param reportEntity
	 */
	public String createReport( ReportEntity reportEntity) throws BusinessException{
		String id=UUID.randomUUID().toString();
		if(!StringUtil.isBlank(reportEntity.getId())){//判断传来的实体类中是否有id，如果有就更新，如果没有就添加
			ReportEntity report = reportMapper.retrieveReportById(reportEntity.getId());
			if(report!=null){
				if(report.getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_SAVE)){
					reportMapper.updateReport(reportEntity);
				}
				
				if(report.getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_COMMIT)){
					throw new  BusinessException(ExceptionConstant.REPORT_ONLY_ONE_CODE,ExceptionConstant.REPORT_ONLY_ONE_NAME);
				}
				
				if(report.getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_REVIXE)){
					reportEntity.setTimesOfReport(report.getTimesOfReport());
					reportEntity.setId(id);
					reportEntity.setProjectStatus(AuditConstant.AUDIT_SAVE);
					reportEntity.setAuditResult(AuditConstant.AUDIT_NOT_EVALUATED);
					reportMapper.createReport(reportEntity);
				}
			}
		}else{
			//查出数据库中的申报基本信息的条数，如果没有就设置为第一次申报，如果有找出最大的申报次数加1
		List<ReportEntity> reportEntitys = reportMapper.retrieveReportByProvinceCodeAndYear(reportEntity.getDivisionCode(),reportEntity.getYear());
		if(reportEntitys.size()==0){
			reportEntity.setId(id);
			reportEntity.setTimesOfReport(1);
			reportEntity.setProjectStatus(AuditConstant.AUDIT_SAVE);
			reportEntity.setAuditResult(AuditConstant.AUDIT_NOT_EVALUATED);
			 reportMapper.createReport(reportEntity);
		} else{
			if(reportEntitys.get(0).getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_SAVE)){
				throw new  BusinessException(ExceptionConstant.REPORT_SAVE_CODE,ExceptionConstant.REPORT_SAVE_NAME);
			}
			
			if(reportEntitys.get(0).getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_COMMIT)){
				throw new  BusinessException(ExceptionConstant.REPORT_ONLY_ONE_CODE,ExceptionConstant.REPORT_ONLY_ONE_NAME);
			}
			if(reportEntitys.get(0).getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_FINISH)){
				throw new  BusinessException(ExceptionConstant.REPORT_FINSH_CODE,ExceptionConstant.REPORT_FINSH_NAME);
			}
			if(reportEntitys.get(0).getProjectStatus().equalsIgnoreCase(AuditConstant.AUDIT_REVIXE)){
				reportEntity.setTimesOfReport(reportEntitys.get(0).getTimesOfReport()+1);
				reportEntity.setId(id);
				reportEntity.setProjectStatus(AuditConstant.AUDIT_SAVE);
				reportEntity.setAuditResult(AuditConstant.AUDIT_NOT_EVALUATED);
				reportMapper.createReport(reportEntity);
			}
		 }
	 }
		return id;
}

	/**
	 * 通过ID删除
	 * @param id
	 */
	public void deleteReport(String id) {
		 reportMapper.deleteReport(id) ;
	}

	/**
	 * 整体审核表 --修改(用于审核表中的审核结果的变化，对应的申报表中的评定结果和申报状态的改变，
	 * 其中保存和申报是原始状态，建议修改和申报完成是变化后的状态，其中申报表的id会重审核表中取出来)
	 * 1.当二次保存的时候用此方法。2.点击提交的时候用到此方法。3.当审核表中的审核状态变化的时候用到此表
	 * @param reportEntity 申报表的实体类
	 */
	public void updateReport( ReportEntity reportEntity) throws BusinessException{
		ReportEntity report = reportMapper.retrieveReportById(reportEntity.getId());
		MapEntity mapEntity=new MapEntity();
		if(report.getProjectStatus().equals(AuditConstant.AUDIT_COMMIT)){//判断是否为二次提交 如果为二次提交就返回消息
			throw new  BusinessException(ExceptionConstant.REPORT_ONLY_ONE_CODE,ExceptionConstant.REPORT_ONLY_ONE_NAME);
		}
		if(report.getProjectStatus().equals(AuditConstant.AUDIT_SAVE)){
			report.setProjectStatus(AuditConstant.AUDIT_COMMIT);
			report.setAuditResult(AuditConstant.AUDIT_NOT_EVALUATED);
			report.setCommitTime(reportEntity.getCommitTime());
			mapEntity.setDivisionCode(report.getDivisionCode());
			mapEntity.setProjectStatue(AuditConstant.AUDIT_COMMIT);
		}
		 mapEntityMapper.updateMapEntity(mapEntity);
		 reportMapper.updateReport(report);
	}
	
	/**
	 * 整体审核表 --修改
	 * @param reportEntity 申报表的实体类
	 */
	public void updateReportForFilePath( ReportEntity reportEntity)throws BusinessException{
		reportMapper.updateReport(reportEntity);
	}

	/**
	 * 通过ID查询
	 * @param id
	 * @return
	 */
	public ReportEntity retrieveReportById(String id) {
		return reportMapper.retrieveReportById(id);
	}

	/**
	 * 根据省区域编码和年份得到申报表并显示出对应的状态 如果不穿参数(如果不传参，就全部查出来，规財司。传年份、省区域编码用于省级的查询)
	 * @param divisionCode 省区域编码
	 * @param year 年份
	 * @return
	 */
	public List<ReportEntity> retrieveReports() {
		return reportMapper.retrieveReports();
	}

	/**
	 * 全部查询（这个方法用来显示查看页面的全部申报表（按时间降序排序）规財司用到）
	 * @return
	 */
	public List<ReportEntity> retrieveReport(
			RetrieveReportData reportDto) {
		
		return reportMapper.retrieveReport(reportDto);
	}

	/**
	 * 通过省级区划代码和年份查询申报
	 */
	public List<ReportEntity> retrieveReportByDivisionCodeAndYear(
			String division, String year) {
		return reportMapper.retrieveReportByProvinceCodeAndYear(division, year);
	}
	
	/**
	 * 查询申报表
	 * 此方法针对于规財司（规划财务司 Department of planning and Finance）
	 * @param reportDto
	 * @return
	 */
	public List<ReportEntity> retrieveReportForDOPAF(RetrieveReportData reportDto){
		return reportMapper.retrieveReportForDOPAF(reportDto);
	}

	/**
	 * 省级主管部门去重查询
	 * @return
	 */
	public List<ReportEntity> distinctProvincialGovernment() {
		return reportMapper.distinctProvincialGovernment();
	}
	
	public void createService(List<ReportEntity> reportEntitys,TargetsOfImplPhaseEntity targetsOfImplPhaseEntity){
		
			//查出数据库中的申报基本信息的条数，如果没有就设置为第一次申报，如果有找出最大的申报次数加1
		for(int j=0;j<reportEntitys.size();j++){
		
			 if(targetsOfImplPhaseEntity==null){
					throw new  BusinessException(ExceptionConstant.DATA_NULL_CODE,ExceptionConstant.DATA_NULL_MESSAGE);
				}
				String idd=UUID.randomUUID().toString();;
					//ReportEntity report= reportMapper.retrieveReportById(id);
							//因为实体类中没有编号，后台自动生成一个id
							targetsOfImplPhaseEntity.setId(idd);
							targetsOfImplPhaseEntity.setReportId(reportEntitys.get(j).getId());
							targetsOfImplPhaseMapper.createTargetsOfImplPhase(targetsOfImplPhaseEntity);
							List<AnnualTargetEntity> annualTargetEntitys=targetsOfImplPhaseEntity.getAnnualTargetDatalist();
							List<AnnualTargetEntity> anns=new ArrayList<AnnualTargetEntity>();
							List<IndexEntity> indexs=new ArrayList<IndexEntity>();
							if(annualTargetEntitys!=null&&annualTargetEntitys.size()>0){
								for(int i=0;i<annualTargetEntitys.size();i++){
									AnnualTargetEntity annT = annualTargetEntitys.get(i);
									annT.setId(UUID.randomUUID().toString());
									annT.setTargetsOfImplPhase(idd);
									anns.add(annT);
								}
								annualTargetMapper.createAnnualTargets(anns);//批量创建年度目标
							}
							List<IndexEntity> indexEntitys=targetsOfImplPhaseEntity.getIndexEntityList();
							if(indexEntitys!=null&&indexEntitys.size()>0){
								for(int i=0;i<indexEntitys.size();i++){
									IndexEntity index = indexEntitys.get(i);
									index.setId(UUID.randomUUID().toString());
									index.setTargetsOfImplPhase(idd);
									indexs.add(index);
								}
								indexMapper.createIndexs(indexs);//批量创建指标
							}
						}
	}
	
	/**
	 * 查询申报导出给Excal
	 * @param reportDto
	 * @return
	 */
	public List<ReportDataToExcel> retrieveReportForDOPAFToExcel(RetrieveReportData reportDto){
		return reportMapper.retrieveReportForDOPAFToExcel(reportDto);
	}
	
	/**
	 * 规財是查询总体实施期目标
	 */
	public List<ReportEntity> retrieveReportForDOPAF2(String divisionCode) {		
		return  reportMapper.retrieveReportForDOPAF2(divisionCode);
	}
	
	/**
	 * 其他司和财政部查看申报表
	 * @return
	 */
	public   List<ReportEntity>   retrieveReportForOtherDepartment(RetrieveReportData retrieveReportData){
		return reportMapper.retrieveReportForOtherDepartment(retrieveReportData);
	}
	/**
	 * 根据省区去编码查询申报表信息
	 * @param divisionCode
	 * @return 申报表实体集合
	 */
	public List<ReportEntity>  retrieveReportsByDIVISIONCODE(String divisionCode){
		return reportMapper.retrieveReportsByDIVISIONCODE(divisionCode);
	}
	
	/**
	 * 规財是参看省局默认指标参考值是否填完
	 * @param referValueFinshCount
	 * @return
	 */
	public List<ReportRemindData>  retrieveReportsForRemind(Integer referValueFinshCount){
		return reportMapper.retrieveReportsForRemind(referValueFinshCount);
	}
	
	/**
	 * 其他司查看申报信息
	 * @param orgId 组织机构id
	 * @return List<ReportEntity> 申报信息列表
	 */
	public List<ReportEntity> retrieveReportForOtherDepartment(String orgId){
		List<String> reportIds=targetsOfImplPhaseMapper.retrieveReportIdByOrgId(orgId);
		List<ReportEntity> retrieveBathReports = reportMapper.retrieveBathReport(reportIds);
		return retrieveBathReports;
	}
	
	/**
	 * 每个司局查出对应省局下的实施期目标
	 * @param reportId
	 * @param orgId
	 * @return
	 */
	public List<TargetsOfImplPhaseEntity> retrieveOtherDepartmentTargetPhaseByReportIdAndOrgId(String reportId,String orgId){
		return reportMapper.retrieveOtherDepartmentTargetPhaseByReportIdAndOrgId(reportId, orgId);
	}
}
